﻿using Consul;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace MuXue.Zyiz.Template.Common
{
    /// <summary>
    /// 
    /// </summary>
    public class ConsulHelper
    {
        /// <summary>
        /// 根据consul服务名查询服务地址
        /// </summary>
        /// <param name="serviceName">consul服务名</param>
        /// <returns>随机返回一条可用的地址</returns>
        public static  string GetServiceBaseUrlByServiceName(string serviceName)
        {
            //第3 个参数表示是否支持热更新，ture表示支持热更新；
            IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", true, true);
            //2、Build一下,用对象IConfigurationRoot接收配置文件内容
            IConfigurationRoot configruation = builder.Build();
            string consulServerUrl = configruation["ConsulConfig:ConsulAddress"].ToString();


            using (ConsulClient client = new Consul.ConsulClient(c =>
            {
                c.Address = new Uri(consulServerUrl);
                c.Token = "";
            }))
            {
                //这里建议加几秒钟缓存抗大量并发请求
                var services = client.Health.Service(serviceName, string.Empty, true);

                ServiceEntry[] servicelist = services.Result.Response;

                string serviceHost;
                if (servicelist.Length == 0)
                {
                    serviceHost = string.Empty;
                }
                else if (servicelist.Length == 1)
                {
                    serviceHost = $"http://{servicelist[0].Service.Address}:{servicelist[0].Service.Port}";
                }
                else
                {
                    var service = servicelist[new Random().Next(0, servicelist.Length)].Service;
                    serviceHost = $"http://{service.Address}:{service.Port}";
                }

                return serviceHost;
            }
        }
    }
}
